export default class AudioObserver {
  private static instance: AudioObserver;
  private subscribers: { audioComponentId: any; callback: () => void }[] = [];

  // 单例模式
  static getInstance(): AudioObserver {
    if (!AudioObserver.instance) {
      AudioObserver.instance = new AudioObserver();
    }
    return AudioObserver.instance;
  }

  subscribe(audioComponentId: any, callback: () => void): void {
    this.subscribers.push({ audioComponentId, callback });

    this.listSubscribers();
  }

  unsubscribe(audioComponentId: any): void {
    this.subscribers = this.subscribers.filter(subscriber => subscriber.audioComponentId !== audioComponentId);
  }

  unsubscribeAll(): void {
    this.subscribers = [];
  }

  // 查看订阅的音频组件
  listSubscribers(): void {
    // console.log('Subscribed audio components:');
    this.subscribers.forEach(subscriber => {
      // console.log(`- ${subscriber.audioComponentId} ====> `, subscriber);
    });
  }

  pauseOthers(currentAudioComponentId: string): void {
    for (const subscriber of this.subscribers) {
      if (subscriber.audioComponentId !== currentAudioComponentId) {
        subscriber.callback();
      }
    }
  }

  play(audioComponentId: string): void {
    const subscriber = this.subscribers.find(subscriber => subscriber.audioComponentId === audioComponentId);
    if (subscriber) {
      // 暂停除了当前音频组件之外的其他音频组件
      this.pauseOthers(audioComponentId);
    } else {
      console.error(`Audio component with ID ${audioComponentId} not found.`);
    }
  }
}
